<template>
  <canvas ref="canvasRef" class="scene-canvas" />
  <div class="absolute top-5 left-5">
    <a-radio-group v-model="radioValue" @change="radioChange">
      <a-radio value="1">第一阶段</a-radio>
      <a-radio value="3">第二阶段</a-radio>
      <a-radio value="4">第三阶段</a-radio>
    </a-radio-group>
  </div>
</template>

<script setup lang="ts">
import * as THREE from 'three'
import { useWindowSize } from '@vueuse/core'
const { width, height } = useWindowSize()
import { threeTool, LightClass } from '@/utils/threeClass'
import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader'
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader'
const canvasRef = ref()
const web3Dtool = new threeTool()
const lightTool = new LightClass()
const radioValue = ref('1')
const objectUUID = ref('')
const initLight = () => {
  const scene = web3Dtool.scene

  var ambientLight = new THREE.AmbientLight(0xffffff, 2) // 创建环境光对象
  scene.add(ambientLight) // 将环境光添加到场景中

  var pointLight = new THREE.PointLight(0xffffff, 0.5, 100) // 创建点光源对象
  pointLight.position.set(0, 0, 0) // 设置点光源位置
  // scene.add(pointLight); // 将点光源添加到场景中
}

const initModel = async (modelName = '1') => {
  const scene = web3Dtool.scene

  const mtlLoader = new MTLLoader().setPath('/models/')
  const materials = await mtlLoader.loadAsync(modelName + '.mtl')
  materials.preload()

  const objLoader = new OBJLoader().setPath('/models/')
  objLoader.setMaterials(materials) // optional since OBJ assets can be loaded without an accompanying MTL file

  const object = await objLoader.loadAsync(modelName + '.obj')

  object.children.forEach(function (child) {
    child.material.color = new THREE.Color(0xffffff)
  })

  object.position.y = -1
  object.scale.setScalar(0.03)
  object.rotation.x = -Math.PI / 2
  scene.add(object)

  objectUUID.value = object.uuid
}
const radioChange = (e: any) => {
  removeModelByUUID(objectUUID.value)
  initModel(e)
}

function removeModelByUUID(uuid: string) {
  const scene = web3Dtool.scene
  const objectToRemove = scene.getObjectByProperty('uuid', uuid)
  if (objectToRemove) {
    scene.remove(objectToRemove)
  } else {
    console.error('Object with UUID not found in the scene.')
  }
}
onMounted(() => {
  web3Dtool.setCanvasMain({ bgColor: 0xcccccc, canvasEl: canvasRef.value })
  web3Dtool.initScene()
  web3Dtool.animateFun()

  initLight()
  initModel()
})

// 5. 监听窗口大小变化
watch([width, height], e => {
  web3Dtool.watchUpdate(e[0], e[1])
})
</script>

<style scoped lang="scss">
.scene-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  outline: none;
}
</style>
